﻿using System.Linq.Expressions;

namespace YK.Console.Business.DataDictItems;

internal class CreateDataDictItemHandler(IRepository<DataDictItemInfo> _repo) : IRequestHandler<CreateDataDictItemRequest, Guid>
{
    public async Task<Guid> Handle(CreateDataDictItemRequest request, CancellationToken cancellationToken)
    {
        var entity = request.Adapt<DataDictItemInfo>();
        await _repo.AddAsync(entity, cancellationToken);
        return entity.Id;
    }
}

internal class UpdateDataDictItemHandler(IRepository<DataDictItemInfo> _repo) : IRequestHandler<UpdateDataDictItemRequest, Guid>
{
    public async Task<Guid> Handle(UpdateDataDictItemRequest request, CancellationToken cancellationToken)
    {
        var entity = await _repo.GetByIdAsync(request.Id, cancellationToken)
            ?? throw ResultOutput.Exception("字典子项不存在");
        entity.Update(request.Code, request.Value, request.Sort, request.ThemeStyle, request.Remark, request.Enabled);
        await _repo.UpdateAsync(entity, cancellationToken);
        return entity.Id;
    }
}

internal class DeleteDataDictItemHandler(IRepository<DataDictItemInfo> _repo) : IRequestHandler<DeleteDataDictItemRequest, int>
{
    public Task<int> Handle(DeleteDataDictItemRequest request, CancellationToken cancellationToken)
        => _repo.DeleteAsync(x => x.Id == request.Id, cancellationToken);
}

internal class DataDictItemSearchHandler(IReadRepository<DataDictItemInfo> _repo) : IRequestHandler<DataDictItemSearchRequest, List<DataDictItemOutput>>
{
    public Task<List<DataDictItemOutput>> Handle(DataDictItemSearchRequest request, CancellationToken cancellationToken)
    {
        Expression<Func<DataDictItemInfo, bool>>? expression = request.Enabled.HasValue
          ? x => x.Enabled == request.Enabled
          : null;
        return _repo.SimpleListAsync<DataDictItemOutput>(request, expression, cancellationToken: cancellationToken);
    }
}


internal class DataDictItemPageHandler(IReadRepository<DataDictItemInfo> _repo) : IRequestHandler<DataDictItemPageRequest, PaginationResponse<DataDictItemOutput>>
{
    public Task<PaginationResponse<DataDictItemOutput>> Handle(DataDictItemPageRequest request, CancellationToken cancellationToken)
        => _repo.SimplePageAsync<DataDictItemOutput>(request, cancellationToken: cancellationToken);
}
